package com.situ.mall.controller;

import com.situ.mall.pojo.User;
import com.situ.mall.service.IUserService;
import com.situ.mall.util.Result;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping("/login")
    public Result login(String name, String password, HttpSession session) {
        User user = userService.login(name, password);
        if (user == null) {
            return Result.error("用户名或密码错误");
        }

        session.setAttribute("user", user);
        return Result.ok("登录成功");
    }

    @RequestMapping("/logout")
    public Result logout(HttpSession session) {
        session.removeAttribute("user");

        return Result.ok("退出成功");
    }

    @RequestMapping("/resetPassword")
    public Result resetPassword(String password, String newPassword, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (!user.getPassword().equals(password)) {
            return Result.error("原密码错误");
        }
        userService.updatePassword(user.getId(), newPassword);
        session.removeAttribute("user");
        return Result.ok("更新成功");
    }
}
